//
//  SightseeingViewController.m
//  Lovelife
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SightseeingViewController.h"
#import "AFNetWorkingYU.h"
#import "ContinentModel.h"
#import "CountryViewController.h"
#import "UIImageView+WebCache.h"
// 城市
#import "CityViewController.h"
// 头部
#import "SightseeingReusableView.h"
#import "NightManager.h"
#import "BaseTableViewCell.h"
#import "AiyouDataBase.h"

@interface SightseeingViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,BaseCollectionReusableViewDelegate>
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicatorView;
@property (nonatomic, retain) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *arrayOfContinent; // 七大洲数组
@property (nonatomic, assign) NSInteger continentIndex;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arrayOfContinentFromFile;
@property (nonatomic, retain) NSString *filePath;
@end

@implementation SightseeingViewController
- (void)dealloc
{
    [_activityIndicatorView release];
    [_flowLayout release];
    [_collectionView release];
    [_arrayOfContinent release];
    [_tableView release];
    [_arrayOfContinentFromFile release];
    [_filePath release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayOfContinent = [NSMutableArray array];
        self.continentIndex = 0;
        self.filePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"continent.plist"];
        self.arrayOfContinentFromFile = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"爱游";
    self.view.backgroundColor = [UIColor whiteColor];
    // 旋转进度轮
    self.activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 50, 150, 100, 100)] ;
    [self.activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleWhiteLarge];
    self.activityIndicatorView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.activityIndicatorView];
    [_activityIndicatorView release];
    [self getDataFromDataBase];
    
}
- (void)getDataFromDataBase
{
    if (self.arrayOfContinentFromFile.count == 0) {
        [self getDataFromNet];
    }else{
        [[AiyouDataBase getDataBase]openDB];
        for (int i = 0; i < 7; i ++) {
            ContinentModel *continent = [[ContinentModel alloc]init];
            ContinentModel *continent2 = self.arrayOfContinentFromFile[i];
            continent.continenId = continent2.continenId;
            continent.cnname = continent2.cnname;
            NSLog(@"%d-%d",continent.hot_country.count,continent.country.count);
            continent.hot_country = [[AiyouDataBase getDataBase]selectCountry:YES continentId:continent.continenId];
            continent.country = [[AiyouDataBase getDataBase]selectCountry:NO continentId:continent.continenId];
            [self.arrayOfContinent addObject:continent];
            [continent release];
        }
        [self createView];
        [self changeContinent:0];
    }
}
- (void)createView
{
    // 创建Item
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.flowLayout.itemSize = CGSizeMake(130, 180);
    self.flowLayout.minimumInteritemSpacing = 10;
    self.flowLayout.minimumLineSpacing = 20;
    self.flowLayout.scrollDirection = 0;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(40, 20, 0, 20);
    // 头部大小
    self.flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 220);
    self.flowLayout.footerReferenceSize = CGSizeMake(100, 240);
    [_flowLayout release];
    
    // 创建瀑布流
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:self.flowLayout];
    [NightManager setBackgroundColorWithCollectionView:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    [_collectionView release];

    ContinentModel *continent = self.arrayOfContinent[0];

    // 创建列表
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45 * continent.country.count) style:UITableViewStylePlain];
    self.tableView.scrollEnabled = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [_tableView release];
    // 注册
    [self.collectionView registerClass:[CountryCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.collectionView registerClass:[SightseeingReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];
}

- (void)getDataFromNet
{
    
    [self.activityIndicatorView startAnimating];
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:@"http://open.qyer.com/qyer/footprint/continent_list?app_installtime=1429487962&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88299841813002&lon=121.5398914286667&page=1&track_app_channel=App%2520Store&track_app_version=6.2&track_device_info=iPhone%25204S&track_deviceid=A902EA06-0821-4413-B962-992BC50581A7&track_os=ios%25207.1.1&v=1" resultBlock:^(id result) {
        NSLog(@"success");
        NSArray *array =result[@"data"];
        [[AiyouDataBase getDataBase] openDB];
        NSMutableArray *a = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            // 解析外层七大洲字典
            ContinentModel *continent = [[ContinentModel alloc]init];
            [continent setValuesForKeysWithDictionary:dic];
            ContinentModel *continent2 = [[ContinentModel alloc]init];
            continent2.cnname = continent.cnname;
            continent2.continenId = continent.continenId;
            [a addObject:continent2];
            NSLog(@"--%@",continent2.cnname);
            [continent2 release];
            // 热门国家数组
            NSMutableArray *hot_country = dic[@"hot_country"];
            // 解析大洲内热门国家数组
            continent.hot_country = [NSMutableArray array];
            for (NSDictionary *dic in hot_country) {
                CountryModel *country = [[CountryModel alloc]init];
                [country setValuesForKeysWithDictionary:dic];
                country.ifHot = YES;
                country.continentId = continent.continenId;
                [continent.hot_country addObject:country];
                [[AiyouDataBase getDataBase]insertCountry:country];
                [country release];
            }
            // 其他国家数组
            NSMutableArray *country = dic[@"country"];
            // 解析大洲内其他国家数组
            continent.country = [NSMutableArray array];
            for (NSDictionary *dic in country) {
                CountryModel *country = [[CountryModel alloc]init];
                [country setValuesForKeysWithDictionary:dic];
                country.ifHot = NO;
                country.continentId = continent.continenId;
                [continent.country addObject:country];
                [[AiyouDataBase getDataBase]insertCountry:country];
                [country release];
            }
            [self.arrayOfContinent addObject:continent];
            [continent release];
        }
        
        [self.activityIndicatorView stopAnimating];
        [self createView];
        [self changeContinent:0];
        
        // 对大洲数组进行归档
        [NSKeyedArchiver archiveRootObject:self.arrayOfContinent toFile:self.filePath];
    }];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    if (self.arrayOfContinent.count == 0) {
//        return 0;
//    }else{
        ContinentModel *continent = self.arrayOfContinent[self.continentIndex];
        return continent.hot_country.count;
//    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CountryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    ContinentModel *continent = self.arrayOfContinent[self.continentIndex];
    CountryModel *country = continent.hot_country[indexPath.row];
    [cell.bgImageView sd_setImageWithURL:[NSURL URLWithString:country.photo] placeholderImage:[UIImage imageNamed:@"3.jpg"]];
    cell.countryNameLable.text = [NSString stringWithFormat:@" %@\n %@",country.cnname,country.enname];
    cell.numberCitiesLabel.text = [NSString stringWithFormat:@"%@\n%@",country.count,country.label];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ContinentModel *continent = self.arrayOfContinent[self.continentIndex];
    return continent.country.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse2";
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[BaseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
    }
    ContinentModel *continent = self.arrayOfContinent[self.continentIndex];
    CountryModel *country = [continent.country objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",country.cnname,country.enname];
    return cell;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        SightseeingReusableView *head = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
        head.delegate = self;
        NSString *name = [self.arrayOfContinent[self.continentIndex] cnname];
        head.nameLabele.text = [NSString stringWithFormat:@"  %@热门目的地",name];
        return head;
    }else{
        UICollectionReusableView *foot = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"foot" forIndexPath:indexPath];
        [foot addSubview:self.tableView];
        return foot;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ContinentModel *continent = self.arrayOfContinent[self.continentIndex];
    CountryModel *country = continent.hot_country[indexPath.row];
    [self push:country];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ContinentModel *continent = self.arrayOfContinent[self.continentIndex];
    CountryModel *country = continent.country[indexPath.row];
    [self push:country];
}
- (void)push:(CountryModel *)country
{
    if (country.flag == 1) {
        CountryViewController *countryVC = [[CountryViewController alloc]init];
        countryVC.countryId = country.countryId;
        [self.navigationController pushViewController:countryVC animated:YES];
        [countryVC release];
    }else{
        CityViewController *city = [[CityViewController alloc]init];
        city.cityId = country.countryId;
        [self.navigationController pushViewController:city animated:YES];
        [city release];
    }
}
- (void)changeContinent:(NSInteger)index
{
    // 更换下标
    self.continentIndex = index;
    // 根据下标获取大洲
     ContinentModel *continent = self.arrayOfContinent[index];
    // tableView大小
    self.tableView.frame = CGRectMake(0, 10, self.view.frame.size.width, 45 * continent.country.count + 30);
    self.flowLayout.footerReferenceSize = self.tableView.frame.size;
    // 更新数据
    [self.tableView reloadData];
    [self.collectionView reloadData];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *name = [self.arrayOfContinent[self.continentIndex] cnname];
    return [NSString stringWithFormat:@"%@其他目的地",name];
}
- (void)setLightDayModel
{
    [NightManager setBackgroundColorWithView:self.tableView];
    [NightManager setBackgroundColorWithView:self.view];
    [NightManager setBackgroundColorWithCollectionView:self.collectionView];
}
- (void)setNightDayModel
{
    [NightManager setBackgroundColorWithView:self.tableView];
    [NightManager setBackgroundColorWithView:self.view];
    [NightManager setBackgroundColorWithCollectionView:self.collectionView];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
